package sample.server;

import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sample.shared.Consts;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;

@SuppressWarnings("serial")
@Singleton
public class GotoServlet extends HttpServlet
{
  private String clientRootDir;

  @Inject
  public GotoServlet(@Named("dir.clientroot") String clientRootDir) {
    this.clientRootDir = clientRootDir;
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response) {
    String code = request.getParameter("clientCode");
    String s =
        "explorer " + "\""
            + ClientManagerServiceImpl.getFileFromCode(clientRootDir, code) + "\""
            + Consts.NEWLINE + "del action*.*" + Consts.NEWLINE;
    try {
      sendBinaryFile(response, s.getBytes(), "action.cm");
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  void sendBinaryFile(HttpServletResponse response, byte[] bytes, String name)
      throws IOException
  {
    response.setContentType("application/octet-stream");
    response.setContentLength(bytes.length);
    response.setHeader("Content-Transfer-Encoding", "binary");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + name
        + "\"");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
    response.setDateHeader("Expires", 0); // Proxies.

    ServletOutputStream stream = response.getOutputStream();
    stream.write(bytes);
    stream.close();
  }
}
